﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using WmsApp.Exceptions;
using WmsApp.Export;
using WmsApp.Factory;
using WmsApp.Security;
using WmsApp.Service;
using WmsApp.Window.Editor;
using WmsApp.WindowControl;
using WmsApp.WmsService;

namespace WmsApp.Window
{
    public partial class FormStockTacking : BaseForm
    {
        private readonly StockTackingController _controller;

        public FormStockTacking()
        {
            InitializeComponent();

            _controller = new StockTackingController(dateEditStockTackingTime, memoEditRemark,
                                                     textEditStockTackingCustomNo, textEditStockTackingDesc,
                                                     textEditStockTackingNo,
                                                     textEditStockTackingYearMonth, gridView3);
        }

        public override string HeadText
        {
            get { return "盘库管理"; }
        }

        private void CmdQuery1_Click(object sender, EventArgs e)
        {
            var condition = qStockTacking1.GetCondition();
            var service =
                EntityServiceFactory.GetEntityService<StockTacking, StockTackingService>();
            gridControlEdit1.DataSource = service.GetEntityList(condition);
        }

        private void CmdNew1_Click(object sender, EventArgs e)
        {
            _controller.NewStockTacking();
            xtraTabControlMain.SelectedTabPage = xtraTabPage3;
        }

        private void CmdEdit1_Click(object sender, EventArgs e)
        {
            var obj = gridView1.GetFocusedRow();
            if (obj != null)
            {
                _controller.LoadStockTacking(((StockTacking) obj).StockTackingNo);
                xtraTabControlMain.SelectedTabPage = xtraTabPage3;
                CmdEnableControl();
            }
        }

// ReSharper disable MemberCanBeMadeStatic.Local
        private void CmdEnableControl()
// ReSharper restore MemberCanBeMadeStatic.Local
        {
        }

        private void CmdQuery2_Click(object sender, EventArgs e)
        {
            var condition = qStockTackingDtl1.GetCondition();
            var service =
                EntityServiceFactory.GetEntityService<ExtendStockTackingDtl, ExtendStockTackingDtlService>();
            gridControlEdit2.DataSource = service.GetEntityList(condition);
        }

        private void CmdNew2_Click(object sender, EventArgs e)
        {
            var obj = gridView2.GetFocusedRow();
            if (obj != null)
            {
                _controller.LoadStockTacking(((ExtendStockTackingDtl) obj).StockTackingNo);
                xtraTabControlMain.SelectedTabPage = xtraTabPage3;
                CmdEnableControl();
            }
        }

        private void CmdEdit2_Click(object sender, EventArgs e)
        {
            var obj = gridView2.GetFocusedRow();
            if (obj != null)
            {
                _controller.LoadStockTacking(((ExtendStockTackingDtl) obj).StockTackingNo);
                xtraTabControlMain.SelectedTabPage = xtraTabPage3;
                CmdEnableControl();
            }
        }

        private void CmdSave3_Click(object sender, EventArgs e)
        {
            _controller.SaveStockTacking();
        }

        private StockTackingDtl InitializeModel(string newGoodsCode, decimal stockTackingQuantity, StoreGoods storeGoods)
        {
            var stockTackingDtl = StockTackingDtl.CreateStockTackingDtl(Constant.NewStockTackingId);

            stockTackingDtl.ISVALID = "1";
            stockTackingDtl.Remark = "";
            stockTackingDtl.NewGoodsCode = newGoodsCode;
            stockTackingDtl.NewGoodsName = storeGoods.NewGoodsName;
            stockTackingDtl.OldGoodsCode = storeGoods.OldGoodsCode;
            stockTackingDtl.StockQuantity = storeGoods.Quantity;
            stockTackingDtl.StockTackingQuantity = stockTackingQuantity;

            return stockTackingDtl;
        }

        private void CmdImport3_Click(object sender, EventArgs e)
        {
            try
            {
                var creator = StockTackingImportorFactory.CreateStockTackingImportor();
                var openFile = new OpenFileDialog();
                openFile.Filter = @"xls|*.xls";
                if (System.Windows.Forms.DialogResult.OK == openFile.ShowDialog())
                {
                    var client = WmsServiceFactory.GetServiceClient();

                    var list = creator.GetImportData(openFile.FileName);
                    var storeGoodsList = new List<StoreGoods>();
                    var stockTackingDtlList = new List<StockTackingDtl>();

                    foreach (var stockTackingDtlModel in list)
                    {
                        var goodsCodeTypeList =
                            client.GetStoreGoodsListByGoodsCodeType(stockTackingDtlModel.NewGoodsCode);

                        if (goodsCodeTypeList.Count > 0)
                        {
                            storeGoodsList.Add(goodsCodeTypeList[0]);
                        }
                        else
                        {
                            var codes =
                                client.GetGoodsCodeTypesByCondition(
                                    string.Format(" and NewGoodsCode='{0}' and  (ExtVarChar3 = '1' or ExtVarChar3 is null or ExtVarChar3 ='' ) ",
                                                  stockTackingDtlModel.NewGoodsCode));
                            if (codes.Count == 0)
                            {
                                ExceptionHandler.ShowException(
                                    string.Format("对不起，物料代码{0}不存在或者已经作废，请确保盘点的代码都是正确的！",
                                                  stockTackingDtlModel.NewGoodsCode));
                                return;
                            }
                            else
                            {
                                //将库存没有的代码导入到库存中，数量为0
                                client.ImportStoreGoods(codes[0].NewGoodsCode);

                                goodsCodeTypeList =
                                    client.GetStoreGoodsListByGoodsCodeType(stockTackingDtlModel.NewGoodsCode);
                                if (goodsCodeTypeList.Count == 0)
                                {
                                    ExceptionHandler.ShowException(
                                        string.Format("对不起，物料代码{0}不存在或者已经作废，请确保盘点的代码都是正确的！",
                                                      stockTackingDtlModel.NewGoodsCode));
                                    return;
                                }
                                storeGoodsList.Add(goodsCodeTypeList[0]);
                            }
                        }
                    }

                    foreach (var stockTackingDtlModel in list)
                    {
                        var model = stockTackingDtlModel;
                        var storeGoods = storeGoodsList.Find(
                            x => x.NewGoodsCode == model.NewGoodsCode);

                        var stockTackingDtl = InitializeModel(stockTackingDtlModel.NewGoodsCode,
                                                              stockTackingDtlModel.TackingQuantity, storeGoods);
                        string msg;
                        var result = ValidateNewGoodsCodeInDtlList(stockTackingDtl, out msg);
                        if (!result)
                        {
                            ExceptionHandler.ShowException(
                                string.Format("对不起，物料代码{0}已经添加入列表中，请先移除或者将xls中的该物料剔除再导入！",
                                              stockTackingDtlModel.NewGoodsCode));
                            return;
                        }
                        stockTackingDtlList.Add(stockTackingDtl);
                    }
                    _controller.AddInStockBillDtl(stockTackingDtlList);
                }
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        private void CmdNewDtl3_Click(object sender, EventArgs e)
        {
            try
            {
                if (!_controller.WrapExist)
                {
                    return;
                }

                var form = new FormStockTackingNewDtlEditor();
                form.ValidateStockTackingDtlExistInList += ValidateNewGoodsCodeInDtlList;
                form.ShowDialog();
                if (form.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    _controller.AddInStockBillDtl(new List<StockTackingDtl> {form.StockTackingDtl});
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.ShowException(ex);
            }
        }

        private bool ValidateNewGoodsCodeInDtlList(StockTackingDtl dtl, out string msg)
        {
            if (_controller.NewGoodsCodeInDtlList(dtl.NewGoodsCode))
            {
                msg = string.Format("物料{0}已经存在盘库明细中！", dtl.NewGoodsCode);
                return false;
            }
            msg = string.Empty;
            return true;
        }

        private void CmdOut_Click(object sender, EventArgs e)
        {
            _controller.OutRange();
        }

        private void CmdNewStockTacking3_Click(object sender, EventArgs e)
        {
            _controller.NewStockTacking();
        }

        private void CmdAllSelect_Click(object sender, EventArgs e)
        {
            _controller.AllSelect();
        }

        private void CmdAllNoSelectClick(object sender, EventArgs e)
        {
            _controller.AllNotSelect();
        }

        private void CmdDeleteDtl_Click(object sender, EventArgs e)
        {
            _controller.DeleteDtl();
        }
    }
}